<template>
  <!-- 地图 -->
  <div class="map">
    <vc-viewer
      ref="viewer"
      :logo="false"
      :infoBox="false"
      :scene3DOnly="true"
      :timeline="false"
      :animation="true"
      :shouldAnimate="true"
      @ready="ready"
      @LEFT_CLICK="LEFT_CLICK"
    >
      <vc-layer-imagery ref="layerText">
        <vc-provider-imagery-tianditu
          :protocol="protocol"
          :mapStyle="mapStyle"
          token="436ce7e50d27eede2f2929307e6b33c0"
        ></vc-provider-imagery-tianditu>
      </vc-layer-imagery>
    </vc-viewer>
  </div>
</template>
<script>
export default {
  data() {
    return {
      mapStyle: 'img_w', // 天地影像图类型
      protocol: 'http', // 天地图请求协议类型
      cesiumInstance: null,
      zoomAmount: 0.5,
      cameraLocation: {}, //摄像头位置
      entities: {
        dots: [], // 点位覆盖图
        areas: [], //区域信息
      },
      trackedUserId: undefined, // 地图跟踪判断条件
      images: {
        park: require('@assets/gis/yuanqu.svg'), //园区
        enterprise: require('@assets/gis/qiye.svg'), //企业
        sensitive: require('@assets/gis/mingandian.svg'), //敏感点
      }, //图标icon
      colors: {
        park: '#5BD0D2',
        enterprise: '#5D98FF',
        sensitive: '#F24747',
      },
      enabled: true,
    }
  },
  methods: {
    ready(cesiumInstance) {
      // gis准备成功事件
      console.log('ready')
      this.cesiumInstance = cesiumInstance
      const { Cesium, viewer } = cesiumInstance
      // 不显示动画控件
      viewer.animation.container.style.visibility = 'hidden'
      //隐藏背景图
      // viewer.scene.sun.show = false //在Cesium1.6(不确定)之后的版本会显示太阳和月亮，不关闭会影响展示
      // viewer.scene.moon.show = false
      // viewer.scene.globe.show = false
      // viewer.scene.skyBox.show = false
      this.$emit('ready')
    },
    gotoDefaultPosition(location) {
      console.log('要去的地址=====', location)
      const { Cesium, viewer } = this.cesiumInstance
      // 进入页面，将地图定位至默认点位
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(location.lng, location.lat, 1500),
      })
      this.cameraLocation = location
    },
    doPostiontwo() {
      this.gotoDefaultPosition(this.cameraLocation)
    },
    LEFT_CLICK(movement) {
      const { viewer } = this.cesiumInstance
      const feature = viewer.scene.pick(movement.position)
      console.log(feature)
      // feature.id：选中的地图覆盖物不一样，id表示的对象也不同，可能为覆盖物的id，也可能为覆盖物本身
      if (feature && feature.id && feature.id.type) {
        let entity = this.entities[feature.id.type][feature.id.id]
        if (entity) {
          this.focusOn(feature.id)
        }
      }
    },
    //聚焦弹窗
    focusOn(feature) {
      const { viewer } = this.cesiumInstance
      viewer.flyTo(this.entities[feature.type][feature.id], { duration: 2.0 })
      //触发回到函数
      this.$emit('showLayer', feature)
    },
    //重置地图数据
    reset() {
      const { viewer } = this.cesiumInstance
      //数据清空
      this.entities.dots = []
      this.entities.areas = []
      viewer.entities.removeAll()
    },
    //放大缩小
    changeZoom(tip) {
      if (!tip) {
        // 镜头拉近
        this.zoom(this.zoomAmount)
      } else {
        // 镜头拉远
        this.zoom(1 / this.zoomAmount)
      }
    },
    //缩放
    zoom(relativeAmount) {
      const { Cesium, viewer } = this.cesiumInstance
      const { camera } = viewer
      let focus = this.getCameraFocus(viewer, Cesium)
      let orientation = {
        direction: camera.direction,
        up: camera.up,
      }
      const cartesian3Scratch = new Cesium.Cartesian3()
      const direction = Cesium.Cartesian3.subtract(camera.position, focus, cartesian3Scratch)
      const movementVector = Cesium.Cartesian3.multiplyByScalar(direction, relativeAmount, direction)
      const endPosition = Cesium.Cartesian3.add(focus, movementVector, focus)
      camera.flyTo({
        destination: endPosition,
        orientation: orientation,
        duration: 0.5,
        convert: false,
      })
    },
    getCameraFocus(scene, Cesium) {
      const { defined, Ellipsoid, IntersectionTests, Ray } = Cesium
      const ray = new Ray(scene.camera.positionWC, scene.camera.directionWC)
      const intersections = IntersectionTests.rayEllipsoid(ray, Ellipsoid.WGS84)
      if (defined(intersections)) {
        return Ray.getPoint(ray, intersections.start)
      }
      // Camera direction is not pointing at the globe, so use the ellipsoid horizon point as
      // the focal point.
      return IntersectionTests.grazingAltitudeLocation(ray, Ellipsoid.WGS84)
    },
    //视觉初始化
    doPostion(viewerLocation) {
      const { Cesium, viewer } = this.cesiumInstance
      if (viewerLocation) {
        let location = viewerLocation.location.split(',')
        viewer.camera.flyTo({
          destination: new Cesium.Cartesian3(location[0], location[1], location[2]),
          orientation: {
            heading: viewerLocation.heading,
            pitch: viewerLocation.pitch,
            roll: viewerLocation.roll,
          },
        })
        return
      }
      // 进入页面，将地图定位至默认展示的厂区位置
      if (!this.cameraLocation.anglePosition) return
      let location = this.cameraLocation.anglePosition.split(',')
      viewer.camera.flyTo({
        destination: new Cesium.Cartesian3(location[0], location[1], location[2]),
        orientation: {
          heading: this.cameraLocation.arcDirection,
          pitch: this.cameraLocation.radian,
          roll: this.cameraLocation.radianAngle,
        },
      })
    },
    // 地图图标覆盖物  地图覆盖物
    showBillboard(dataSource = []) {
      const { Cesium, viewer } = this.cesiumInstance
      // let enabled = true ///是否聚合
      // let pixelRange = 30 //聚合范围（单位px）
      // let minimumClusterSize = 3 //最小聚合数值（小于等于该数值，不聚合）
      // if(dataSource.length<=100) {
      //   pixelRange = 30
      //   minimumClusterSize = 3
      // }
      // if(dataSource.length>100&&dataSource.length<=250) {
      //   pixelRange = 100
      //   minimumClusterSize = 20
      // }
      // let myDataSource = new Cesium.CustomDataSource('myDataSource') //实例化实体级对象（实现，可用于手动管理一组实体）
      dataSource.map((item, index) => {
        console.log('覆盖物信息', item)
        if (item.coordinates) {
          let entityInfo = {
            show: item.show,
            id: item.id,
            type: 'dots',
            dataIndex: index,
            position: Cesium.Cartesian3.fromDegrees(item.coordinates.lng, item.coordinates.lat, 5),
            label: {
              text: item.name,
              font: 'normal 28px PingFangSC-Medium, PingFang SC',
              scale: 0.5,
              showBackground: true,
              backgroundColor: Cesium.Color.BLACK,
              pixelOffset: { x: 0.0, y: -60 },
              distanceDisplayCondition: { near: 0, far: 120000 }, //距离镜头多远的距离将不显示
              disableDepthTestDistance: 5000, //设置标签的显示不会被覆盖
              horizontalOrigin: 0, //左对齐
              verticalOrigin: 0, //垂直居中
            },
            billboard: {
              image: this.images[item.type],
              scale: 1,
              distanceDisplayCondition: { near: 0, far: 5000 }, //距离镜头多远的距离将不显示
              // scaleByDistance: { near: 10, nearValue: 0.7, far: 2000, farValue: 1 },//根据距离镜头的距离等比例缩放图标大小
              disableDepthTestDistance: 5000, //设置图标的显示不会被覆盖
            },
          }
          if (!this.entities['dots'][item.id]) {
            let entity = viewer.entities.add(entityInfo)
            // let entity = myDataSource.entities.add(entityInfo)
            this.entities['dots'][item.id] = entity
          }
        }
      })

      // console.log("这个实例化的什么东西====",myDataSource,this.entities['dots']);
      // //添加entity数组
      // viewer.dataSources.add(myDataSource).then(function (dataSource) {
      //   console.log("这是什么=====",dataSource);
      //   dataSource.clustering.enabled = enabled //是否聚合
      //   dataSource.clustering.pixelRange = pixelRange //聚合范围（单位px）
      //   dataSource.clustering.minimumClusterSize = minimumClusterSize //最小屏幕聚合对象数值（小于等于该数值，不聚合）
        

      // })
    },
    //展示绘制区域
    showColorChart(dataSource = []) {
      const { Cesium, viewer } = this.cesiumInstance
      dataSource.map((item, index) => {
        console.log('区域覆盖信息', item)
        if (item.locations) {
          //设置风险四色图颜色
          let _location = [],
            _minimumHeights = [] //围栏高度
          if (item.type == 'park') {
            item.locations.map((items) => {
              _location.push(parseFloat(items.lng), parseFloat(items.lat), 1.0)
              _minimumHeights.push(parseFloat(50)) //围栏高度
            })
            _location.push(parseFloat(item.locations[0].lng), parseFloat(item.locations[0].lat), 1.0)
            _minimumHeights.push(parseFloat(50)) //围栏高度
          } else {
            item.locations.map((items) => {
              _location.push(parseFloat(items.lng), parseFloat(items.lat))
            })
          }
          let color = new Cesium.Color.fromCssColorString(this.colors[item.type] || 'red')
          let material = color.withAlpha(0.2)
          let entityInfo = {
            id: item.id,
            type: 'areas',
            show: item.show,
            dataIndex: index,
          }
          //园区显示墙
          if (item.type == 'park') {
            entityInfo.wall = {
              positions: Cesium.Cartesian3.fromDegreesArrayHeights(_location),
              material: material,
              minimumHeights: _minimumHeights,
              outline: true,
              outlineColor: color,
              outlineWidth: 2.0,
            }
          } else {
            entityInfo.polygon = {
              hierarchy: Cesium.Cartesian3.fromDegreesArray(_location),
              material: material,
              height: 50,
              extrudedHeight: 0,
              outline: true,
              outlineColor: color,
            }
          }
          if (!this.entities['areas'][item.id]) {
            let entity = viewer.entities.add(entityInfo)
            this.entities['areas'][item.id] = entity
          }
        }
      })
    },
    //删除gis实例
    deleteEntity(info, dataSource) {
      const { viewer } = this.cesiumInstance
      dataSource.map((item) => {
        const _entityId = info + '---' + item.key
        let entity = this.entities[info][_entityId]
        if (entity) {
          viewer.entities.remove(entity)
          delete this.entities[info][_entityId]
        }
      })
    },
    //隐藏实例或者label
    hideModules(flag, type) {
      console.log('触发隐藏')
      const { viewer } = this.cesiumInstance
      let entitys = viewer.entities.values
      if (entitys.length != null && entitys.length > 0) {
        for (let m = 0; m < entitys.length; m++) {
          let entity = entitys[m]
          const entityInfo = entity.id.split('-')
          if (entityInfo[0] == type) {
            entity.show = flag
          }
        }
      }
    },
    //获取当前摄像头数据
    getCurrentView() {
      // 获取当前视角的地图数据
      const { viewer } = this.cesiumInstance
      const obj = {
        location: viewer.camera.position.x + ',' + viewer.camera.position.y + ',' + viewer.camera.position.z,
        heading: viewer.camera.heading,
        pitch: viewer.camera.pitch,
        roll: viewer.camera.roll,
      }
      return obj
    },
  },
}
</script>
<style lang="less" scoped>
.map {
  width: 100%;
  height: 100%;
  position: relative;
  z-index: 1;
}
</style>